package com.qsl.juc.producer_consumer;

/**
 * synchronized 实现生产者与消费者
 *
 * @author 青石路
 * @date 2021/3/15 20:52
 */
public class SynchronizedDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareData.increment();
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareData.decrement();
            }
        }, "t2").start();
    }

    static class ShareData {
        private int num = 0;

        public void increment() {
            synchronized (this) {

                // 防止虚假唤醒，用 while 而不是 if；用 > 2 的线程数去测试
                while (num != 0) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num++;
                System.out.println(Thread.currentThread().getName() + " " + num);
                this.notifyAll();
            }
        }

        public void decrement() {
            synchronized (this) {

                // 防止虚假唤醒，用 while 而不是 if；用 > 2 的线程数去测试
                while (num == 0) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num--;
                System.out.println(Thread.currentThread().getName() + " " + num);
                this.notifyAll();
            }
        }
    }
}
